package com.feiwo.nonego.rpc.common.util;

import io.netty.channel.DefaultSelectStrategyFactory;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.MultiThreadIoEventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollIoHandler;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.kqueue.KQueue;
import io.netty.channel.kqueue.KQueueServerSocketChannel;
import io.netty.channel.nio.NioIoHandler;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.uring.IoUringIoHandler;

/**
 *
 *
 * @author feiwo 2025-08-08
 */
public class NettyUtils {

    /**
     * 根据平台创建最适合的EventLoopGroup
     *
     * @return EventLoopGroup实例
     */
    public static EventLoopGroup createEventLoopGroup(int size) {
        // 优先使用Epoll (Linux)
        if (Epoll.isAvailable()) {
            return new MultiThreadIoEventLoopGroup(EpollIoHandler.newFactory(size, DefaultSelectStrategyFactory.INSTANCE));
        }
        // 其次使用KQueue (macOS/BSD)
        else if (KQueue.isAvailable()) {
            return new MultiThreadIoEventLoopGroup(IoUringIoHandler.newFactory(size));
        }
        // 最后回退到Nio
        else {
            return new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
        }
    }

    /**
     * 根据平台获取最适合的ServerSocketChannel类
     *
     * @return Class<? extends ServerChannel>实例
     */
    public static Class<? extends ServerChannel> getServerSocketChannelClass() {
        // 优先使用Epoll (Linux)
        if (Epoll.isAvailable()) {
            return EpollServerSocketChannel.class;
        }
        // 其次使用KQueue (macOS/BSD)
        else if (KQueue.isAvailable()) {
            return KQueueServerSocketChannel.class;
        }
        // 最后回退到Nio
        else {
            return NioServerSocketChannel.class;
        }
    }

}
